package com.liangxy.news.ui.main.home;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.liangxy.news.R;
import com.liangxy.news.api.ApiClient;
import com.liangxy.news.api.NewsApiService;
import com.liangxy.news.api.NewsResponse;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.model.News;
import com.liangxy.news.util.NetworkUtils;
import com.liangxy.news.util.SharedPreferencesManager;
import com.liangxy.news.repository.NewsRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Home fragment to display news categories and news list
 */
public class HomeFragment extends Fragment {
    
    private static final String TAG = "HomeFragment";
    
    private TabLayout tabLayout;
    private ViewPager2 viewPager;
    private ProgressBar progressBar;
    
    private SharedPreferencesManager preferencesManager;
    private ExecutorService executorService;
    private NewsCategoryAdapter categoryAdapter;
    
    private final List<String> categories = new ArrayList<>();
    private final List<String> categoryTitles = new ArrayList<>();
    private String initialCategory = null; // 用于存储从广告跳转过来的类别
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        // 检查是否有参数传入，用于直接跳转到特定类别
        if (getArguments() != null && getArguments().containsKey("CATEGORY")) {
            initialCategory = getArguments().getString("CATEGORY");
            Log.d(TAG, "接收到初始类别参数: " + initialCategory);
        }
        
        // Initialize components
        tabLayout = view.findViewById(R.id.tabLayout);
        viewPager = view.findViewById(R.id.viewPager);
        progressBar = view.findViewById(R.id.progressBar);
        
        preferencesManager = new SharedPreferencesManager(requireContext());
        executorService = Executors.newSingleThreadExecutor();
        
        // Setup categories
        setupCategories();
        
        return view;
    }
    
    /**
     * Setup news categories
     */
    private void setupCategories() {
        // Get categories from preferences
        String categoriesString = preferencesManager.getNewsCategories();
        String[] categoryArray = categoriesString.split(",");
        
        categories.clear();
        categoryTitles.clear();
        
        categories.addAll(Arrays.asList(categoryArray));
        
        // Add category titles
        for (String category : categories) {
            switch (category) {
                case "top":
                    categoryTitles.add(getString(R.string.category_top));
                    break;
                case "guonei":
                    categoryTitles.add(getString(R.string.category_guonei));
                    break;
                case "guoji":
                    categoryTitles.add(getString(R.string.category_guoji));
                    break;
                case "yule":
                    categoryTitles.add(getString(R.string.category_yule));
                    break;
                case "tiyu":
                    categoryTitles.add(getString(R.string.category_tiyu));
                    break;
                case "junshi":
                    categoryTitles.add(getString(R.string.category_junshi));
                    break;
                case "keji":
                    categoryTitles.add(getString(R.string.category_keji));
                    break;
                case "caijing":
                    categoryTitles.add(getString(R.string.category_caijing));
                    break;
                case "youxi":
                    categoryTitles.add(getString(R.string.category_youxi));
                    break;
                case "qiche":
                    categoryTitles.add(getString(R.string.category_qiche));
                    break;
                case "jiankang":
                    categoryTitles.add(getString(R.string.category_jiankang));
                    break;
                default:
                    categoryTitles.add(category);
                    break;
            }
        }
        
        // Setup adapter
        categoryAdapter = new NewsCategoryAdapter(this, categories);
        viewPager.setAdapter(categoryAdapter);
        
        // Connect TabLayout with ViewPager2
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> 
                tab.setText(categoryTitles.get(position))).attach();
        
        // 如果有初始类别参数，则跳转到对应的类别
        if (initialCategory != null && !initialCategory.isEmpty()) {
            selectCategory(initialCategory);
        }
    }
    
    /**
     * 选择特定的新闻类别
     * @param category 新闻类别
     */
    public void selectCategory(String category) {
        if (category == null || category.isEmpty() || categories.isEmpty()) {
            return;
        }
        
        // 查找类别在列表中的索引
        int index = categories.indexOf(category);
        if (index >= 0) {
            // 切换到对应的类别页
            viewPager.setCurrentItem(index, false);
            Log.d(TAG, "切换到新闻类别: " + category + "，位置: " + index);
        } else {
            Log.w(TAG, "找不到指定的新闻类别: " + category);
        }
    }
    
    /**
     * Load news for a category
     * @param category News category
     * @param callback Callback to receive news list
     */
    public void loadNews(String category, NewsLoadCallback callback) {
        Log.d(TAG, "Loading news for category: " + category);
        
        // 检查是否使用模拟数据
        NewsRepository newsRepository = NewsRepository.getInstance(requireContext());
        boolean useMockData = newsRepository.isUsingMockData();
        
        if (useMockData) {
            Log.d(TAG, "Using mock data for category: " + category);
            // 使用NewsRepository来获取模拟数据
            newsRepository.refreshNewsByCategory(category, 1, 20);
            // 从数据库加载数据（模拟数据会被保存到数据库）
            loadNewsFromDatabase(category, callback);
            return;
        }
        
        // 优先从API加载数据
        if (NetworkUtils.isNetworkAvailable(requireContext())) {
            // 从API加载数据，强制刷新
            loadNewsFromApi(category, callback);
        } else {
            // 如果网络不可用，从数据库加载
            Log.d(TAG, "Network not available, loading from database");
            loadNewsFromDatabase(category, callback);
        }
    }
    
    /**
     * Load news from API
     * @param category News category
     * @param callback Callback to receive news list
     */
    private void loadNewsFromApi(String category, NewsLoadCallback callback) {
        Log.d(TAG, "Loading news from API for category: " + category);
        
        // Load from API
        NewsApiService apiService = ApiClient.getNewsApiService();
        Call<NewsResponse> call = apiService.getNewsList(
                ApiClient.getApiKey(),
                category,
                1,
                30,
                0
        );
        
        call.enqueue(new Callback<NewsResponse>() {
            @Override
            public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    NewsResponse newsResponse = response.body();
                    Log.d(TAG, "API response: " + newsResponse.getReason() + ", code: " + newsResponse.getErrorCode());
                    
                    if (newsResponse.getErrorCode() == 0 && newsResponse.getResult() != null && newsResponse.getResult().getData() != null) {
                        List<News> newsList = newsResponse.getResult().getData();
                        Log.d(TAG, "Received " + newsList.size() + " news items from API");
                        
                        // 更新新闻分类
                        for (News news : newsList) {
                            if (news.getCategory() == null || news.getCategory().isEmpty()) {
                                news.setCategory(category);
                            }
                        }
                        
                        // Save to database
                        saveNewsToDatabase(newsList);
                        
                        // Return news list
                        callback.onNewsLoaded(newsList);
                    } else {
                        // Load from database if API returns error
                        Log.e(TAG, "API error: " + newsResponse.getReason());
                        loadNewsFromDatabase(category, callback);
                    }
                } else {
                    // Load from database if API call fails
                    Log.e(TAG, "API call unsuccessful: " + (response.errorBody() != null ? response.errorBody().toString() : "Unknown error"));
                    loadNewsFromDatabase(category, callback);
                }
            }
            
            @Override
            public void onFailure(Call<NewsResponse> call, Throwable t) {
                // Load from database if API call fails
                Log.e(TAG, "API call failed: " + t.getMessage());
                loadNewsFromDatabase(category, callback);
            }
        });
    }
    
    /**
     * Save news to database
     * @param newsList News list to save
     */
    private void saveNewsToDatabase(List<News> newsList) {
        executorService.execute(() -> {
            try {
                AppDatabase database = AppDatabase.getInstance(requireContext());
                database.newsDao().insertAll(newsList);
                Log.d(TAG, "Saved " + newsList.size() + " news items to database");
            } catch (Exception e) {
                Log.e(TAG, "Error saving news to database: " + e.getMessage());
            }
        });
    }
    
    /**
     * Load news from database
     * @param category News category
     * @param callback Callback to receive news list
     */
    private void loadNewsFromDatabase(String category, NewsLoadCallback callback) {
        Log.d(TAG, "Loading news from database for category: " + category);
        
        try {
            AppDatabase database = AppDatabase.getInstance(requireContext());
            
            if (category.equals("top")) {
                // 对于"推荐"类别，加载所有新闻
                database.newsDao().getAllNews().observe(getViewLifecycleOwner(), newsList -> {
                    if (newsList != null && !newsList.isEmpty()) {
                        Log.d(TAG, "Loaded " + newsList.size() + " news items from database for top category");
                        callback.onNewsLoaded(newsList);
                    } else {
                        Log.d(TAG, "No news found in database for top category");
                        // 如果数据库中没有数据，尝试从API加载
                        if (NetworkUtils.isNetworkAvailable(requireContext())) {
                            loadNewsFromApi(category, callback);
                        } else {
                            callback.onNewsLoadFailed("没有缓存的新闻数据");
                        }
                    }
                });
            } else {
                // 对于其他类别，按类别加载新闻
                database.newsDao().getNewsByCategory(category).observe(getViewLifecycleOwner(), newsList -> {
                    if (newsList != null && !newsList.isEmpty()) {
                        Log.d(TAG, "Loaded " + newsList.size() + " news items from database for category: " + category);
                        callback.onNewsLoaded(newsList);
                    } else {
                        Log.d(TAG, "No news found in database for category: " + category);
                        // 如果数据库中没有数据，尝试从API加载
                        if (NetworkUtils.isNetworkAvailable(requireContext())) {
                            loadNewsFromApi(category, callback);
                        } else {
                            callback.onNewsLoadFailed("没有缓存的新闻数据");
                        }
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading news from database: " + e.getMessage());
            callback.onNewsLoadFailed("加载新闻数据失败");
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (executorService != null) {
            executorService.shutdown();
        }
    }
    
    /**
     * Callback interface for news loading
     */
    public interface NewsLoadCallback {
        void onNewsLoaded(List<News> newsList);
        void onNewsLoadFailed(String errorMessage);
    }
} 